package de.dopichaj.labrador.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public final class Configuration {
    
    private final Properties properties = new Properties();
    
    /**
     * Create an empty configuration.
     */
    public Configuration() {
    }
    
    public Configuration(final InputStream inputStream) throws IOException {
        load(inputStream);
    }
    
    public void load(final File file) throws FileNotFoundException, IOException {
        load(new FileInputStream(file));
    }

    public void load(final InputStream inputStream) throws IOException {
        properties.load(inputStream);
        inputStream.close();
    }
    
    public void setString(final String key, final String value) {
        properties.setProperty(key, value);
    }
    
    public String getString(final String key) {
        
        return properties.getProperty(key);
    }
    
    public String getString(final String key, final String def) {
        
        final String value = getString(key);
        if (value == null) {
            properties.setProperty(key, def);
            return def;
        } else {
            return value;
        }
    }
    
    public int getInt(final String key) {

        return getInt(key, 0);
    }

    public int getInt(final String key, final int def) {
        
        final String value = getString(key);
        if (value == null) {
            properties.setProperty(key, Integer.toString(def));
            return def;
        }
        return Integer.valueOf(value);
    }

    public boolean getBool(final String key, final boolean def) {
        final String value = getString(key);
        if (value == null) {
            properties.setProperty(key, Boolean.toString(def));
            return def;
        }
        return !value.equals("false");
    }
    
    public double getDouble(final String key, final double def) {
        final String value = getString(key);
        if (value == null) {
            properties.setProperty(key, Double.toString(def));
            return def;
        }
        return Double.valueOf(value);
    }
    
    public void save(final OutputStream output) throws IOException {
        properties.store(output, "");
    }
}
